package mediator;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ChatroomMediator implements MessageMediator
{
	private final Map<String, ChatParticipant> participants = new ConcurrentHashMap<>();
	private final MessageFilter messageFilter = new MessageFilter();  // 消息过滤器

	@Override
	public void registerParticipant(ChatParticipant participant) {
		if (participant == null || participant.getName() == null) {
			throw new IllegalArgumentException("参与者信息不能为空");
		}

		participants.put(participant.getName(), participant);
		participant.joinChatroom(this);

		System.out.println(participant.getName() + " 加入了聊天室");
	}

	@Override
	public void routeTextMessage(String senderName, String receiverName, String content) {
		ChatParticipant receiver = participants.get(receiverName);
		if (receiver == null) {
			notifySender(senderName, "用户 " + receiverName + " 不在线");
			return;
		}

		String filteredContent = messageFilter.filterText(content);
		receiver.onTextMessageReceived(senderName, filteredContent);
	}

	@Override
	public void routeImageMessage(String senderName, String receiverName, String imageData) {
		ChatParticipant receiver = participants.get(receiverName);
		if (receiver == null) {
			notifySender(senderName, "用户 " + receiverName + " 不在线");
			return;
		}

		if (messageFilter.validateImageSize(imageData)) {
			receiver.onImageMessageReceived(senderName, imageData);
		} else {
			notifySender(senderName, "图片过大，发送失败");
		}
	}

	@Override
	public void broadcastMessage(String senderName, String content) {

	}

	private void notifySender(String senderName, String notification) {
		ChatParticipant sender = participants.get(senderName);
		if (sender != null) {
			sender.onSystemNotification(notification);
		}
	}
}